import React, { useMemo } from 'react';

import {
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';

export type MyDynamicFieldProps<T = Record<string, any>> = T & {
  name: string;
  label: string;
  placeholder?: string;
  min?: string | number | undefined;
  max?: string | number | undefined;
  defaultValue?: string | number | undefined;
  rules?: any;
  myFieldType: string | undefined;
  initialValue?: any;
};

const MyDynamicField: React.FC<MyDynamicFieldProps> = (props) => {
  //console.log(props);

  const renderContentDom = useMemo(() => {
    if (!props.myFieldType) {
      return null;
    }
    if (props.myFieldType === 'string[]') {
      return <ProFormTextArea fieldProps={{ rows: 8 }} {...props} />;
    } else if (props.myFieldType === 'text') {
      return <ProFormTextArea fieldProps={{ rows: 8 }} {...props} />;
    } else if (props.myFieldType === 'json') {
      return <ProFormTextArea fieldProps={{ rows: 8 }} {...props} />;
    } else if (props.myFieldType === 'string') {
      return <ProFormText {...props} />;
    } else if (props.myFieldType === 'int') {
      return (
        <>
          <ProFormDigit
            {...props}
            fieldProps={{ precision: 0 }}
            wrapperCol={{ span: 8 }}
            addonAfter={
              <span className="ant-form-item-extra">
                [{props.min}-{props.max}]
              </span>
            }
          />
        </>
      );
    } else if (props.myFieldType === 'decimal') {
      return (
        <>
          <ProFormDigit
            {...props}
            fieldProps={{ precision: 2 }}
            wrapperCol={{ span: 8 }}
            addonAfter={
              <span className="ant-form-item-extra">
                [{props.min}-{props.max}]
              </span>
            }
          />
        </>
      );
    } else if (props.myFieldType === 'bool') {
      let items: any[] = ['true', 'false'];

      return <ProFormSelect allowClear={false} options={items} {...props} />;
    } else if (props.myFieldType?.indexOf('select|') === 0) {
      let items: any[] = [];
      try {
        const itemStr = props.myFieldType?.substring(7);
        items = JSON.parse(itemStr);
      } catch (err) {
        //console.log(err);
        items = [];
      }

      return <ProFormSelect allowClear={false} options={items} {...props} />;
    }
    return null;
  }, [props]);

  return renderContentDom;
};

export default MyDynamicField;
